console.group('App')

import * as bundle from './other/bundle'

import * as globalReducer from './reducers/globalReducer'
import * as homeReducer from './reducers/homeReducer'
import * as profileReducer from './reducers/profileReducer'
import * as activityReducer from './reducers/activityReducer'

const {
  regeneratorRuntime,
  createStore, applyMiddleware, combineReducers, compose,
  Provider, connect,
  thunk, logger,
  md5,
  dayjs,
  throttle,
  debounce,
  uniq
} = bundle

global.regeneratorRuntime = regeneratorRuntime
global.navigatorKey = null
global.connect = connect
global.md5 = md5
global.dayjs = dayjs
global.throttle = throttle
global.debounce = debounce
global.uniq = uniq

global.globalReducer = globalReducer
global.homeReducer = homeReducer
global.profileReducer = profileReducer
global.activityReducer = activityReducer

global.navigateTo = data => {
  // console.log('navigatorKey', global.navigatorKey)
  if (!global.navigatorKey) {
    global.navigatorKey = Math.random().toFixed(2)
    wx.navigateTo({
      ...data,
      success(e) { },
      fail(e) { },
      complete() { global.navigatorKey = null }
    })
  } else {
    console.log('global navigator lock')
  }
}

global.redirectTo = data => {
  if (!global.navigatorKey) {
    global.navigatorKey = Math.random().toFixed(2)
    wx.redirectTo({
      ...data,
      success(e) { },
      fail(e) { },
      complete() { global.navigatorKey = null }
    })
  } else {
    console.log('global navigator lock')
  }
}

const pages = {}
const routes = [
  "pages/login/login",
  "pages/login/forget/forget",
  "pages/index/index",
  "pages/share/share",
  "pages/profile/history/history",
  "pages/profile/history/activity/activity",
  "pages/profile/setting/setting",
  "pages/profile/setting/modpwd/modpwd",
  "pages/profile/setting/modphone/modphone",
  "pages/profile/setting/feedback/feedback",
  "pages/profile/setting/store/store",
  "pages/create-activity/create-activity",
  "pages/index/activity-detail/activity-detail",
  "pages/index/order-detail/order-detail",
  "pages/index/make-order-step1/make-order-step1",
  "pages/index/make-order-step2/make-order-step2",
  "pages/index/make-order-step2/mos-step0/mos-step0",
  "pages/index/make-order-step2/mos-step1/mos-step1",
  "pages/index/make-order-step2/mos-step2/mos-step2",
  "pages/index/make-order-step3/make-order-step3",
  "pages/index/effect/effect",
  "pages/index/image-select/image-select",
  "pages/index/effect-custom/effect-custom"
].map(i => {
  const key = i.substring(i.lastIndexOf('/') + 1)
  const val = '/' + i
  pages[key] = val
  return { key, val }
})

global.pages = pages
global.routes = routes

global.handleRoute = e => {
  const playload = e.currentTarget ? e.currentTarget.dataset : e
  const { route, type = 'navigateTo', query, param } = playload
  let url = global.pages[route || path]
  if (url) {
    let obj = []
    if (query) {
      Object.keys(query).map(key => {
        obj.push(`${key}=${query[key]}`)
      })
      url += `?${obj.join('&')}`
    }
    global[type] && global[type]({ url })
  } else {
    console.error('route not found', playload.route)
  }
}

global.P = (obj) => {
  const m = (el, obj) => {
    const elKeys = Object.keys(el);
    el.data = el.data || {};
    elKeys.forEach((e) => {
      e === "data" && Object.assign(obj.data, el.data);
      (e !== "data") && (obj[e] = el[e]);
    })
  }

  const { mixins = [] } = obj;
  Reflect.deleteProperty(obj, 'mixins');
  obj.data = obj.data || {};
  mixins.forEach((el) => {
    m(el, obj)
  })
  return obj;
}

const store = global.store = createStore(
  combineReducers({
    globalReducer: globalReducer.reducer,
    homeReducer: homeReducer.reducer,
    profileReducer: profileReducer.reducer,
    activityReducer: activityReducer.reducer
  }),
  compose(applyMiddleware(thunk, logger))
)

global.waitUntilLogin = fn => {
  let hasLogined = false
  const key = setInterval(() => {
    if (store.getState().globalReducer.minaLoginRes.apiCode === 200) {
      hasLogined = true
    }
    if (hasLogined) {
      fn && fn()
      clearInterval(key)
    }
  }, 100)
}

const config = {
  async onLaunch() {
    console.log('App onLaunch');

    store.dispatch(globalReducer.getSystemInfo)(store.dispatch);

    const preLoginRes = await store.dispatch(globalReducer.minaLogin)(store.dispatch);

    console.log('preLoginRes', preLoginRes);

    if (preLoginRes.actionStatus === 'SUCCESS') {
      console.log('已绑定，自动跳转');
      const intervalKey = setInterval(() => {
        const pages = getCurrentPages()
        if (pages.length) {
          clearInterval(intervalKey)

          const systemInfo = store.getState().globalReducer.minaSystemInfo;
          if (systemInfo && systemInfo.brand === 'devtools') {
            return;
          }

          const url = pages[pages.length - 1].route;
          if (url.indexOf('/share')) {
            return;
          }
          global.handleRoute({ route: 'index', type: 'redirectTo' });
        }
      }, 50)
    }

    console.groupEnd()
  },
  onError(e) {
    console.error(e)
  }
}

App(Provider(store)(config))
